<template>
    <el-container>
        <el-header class='el-header'>
            <div style="font-size:24px;color:#333333;text-align:left;margin-left:50px;margin-top:30px;">
                自定义知识图谱
            </div>
            <div style="font-size:12px;color:#333333;text-align:left;margin-left:50px;margin-top:4px;">
                用户输入结构化文本 实现自定义知识图谱
            </div>
        </el-header>

        <el-container ref="containerRef">
            <el-main class="main">
            <div id="myChart" :style="{width: chartWidth, height: chartHeight}"></div>
            </el-main>

            <el-aside class="info">
                <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
                    <el-tab-pane label="搜索" name="first">
                        <el-autocomplete
                        class="inline-input"
                        v-model="input"
                        :fetch-suggestions="querySearch"
                        placeholder="请输入查找的实体"
                        @select="handleSelect"
                        clearable
                        style="margin-top:10px;"></el-autocomplete>
                        <el-button class="btn" icon="el-icon-search" @click="searchQuery()" circle></el-button>
                        <div style="margin-top:30px;font-size:14px;color:#606266;text-align:left;margin-left:30px;">
                            点击查询节点
                        </div>
                        <h2 style="margin-top:4px;margin-left:30px;margin-right:30px;height:1px;background-color:#C0C4CC"></h2>
                        <div>
                            <el-button v-for="(entity, index) in entities" :key="index" @click="searchEntity(entity)" round plain type="primary" size="small" style="margin-left:10px;margin-bottom:12px">
                                {{ entity }}
                            </el-button>
                        </div>
                        <div style="margin-top:10px;font-size:14px;color:#606266;text-align:left;margin-left:30px;">
                            点击查询关系
                        </div>
                        <h2 style="margin-top:4px;margin-left:30px;margin-right:30px;height:1px;background-color:#C0C4CC"></h2>
                        <div>
                            <el-button v-for="(relation, index) in relations" :key="index" @click="searchRelation(relation)" round plain type="primary" size="small" style="margin-left:10px;margin-bottom:12px">
                                {{ relation }}
                            </el-button>
                        </div>
                    </el-tab-pane>

                    <el-tab-pane label="信息" name="second">
                        <div style="margin-top:20px;font-size:20px;color:#333333;text-align:left;margin-left:40px;">
                            {{graphName}}知识图谱
                        </div>
                        <div style="margin-top:30px;font-size:14px;color:#b5b5b5;text-align:left;margin-left:40px;">
                            当前{{selectElement}}信息
                        </div>
                        <transition name="el-zoom-in-top">
                        <div v-show="infoshow" class="table-content">
                            <el-table
                                :show-header="false"
                                :data="list"
                                class="mt-10"
                                fit
                                empty-text="暂无数据"
                                :highlight-current-row="true"
                                style="margin-top:10px;"
                            >
                                <el-table-column align="center">
                                    <template slot-scope="scope">
                                    <template>
                                        <el-tag>{{scope.row.id}}</el-tag>
                                    </template>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                v-for="(item, index) in table_title"
                                :key="index"
                                :prop="item.prop"
                                :label="item.label"
                                >
                                </el-table-column>

                            </el-table>
                        </div>
                        </transition>
                        <el-tooltip class="item" effect="dark" :content="'仅显示该'+selectElement" placement="bottom">
                        <el-button :disabled="deleteBtnShow" @click="showElementOnly()" type="success" class="delete-btn" icon="el-icon-search" circle plain style="margin-top:14px;"></el-button>
                        </el-tooltip>

                        <el-tooltip class="item" effect="dark" :content="'删除该'+selectElement" placement="bottom">
                        <el-button :disabled="deleteBtnShow" type="info" @click="dialogVisible = true" class="delete-btn" icon="el-icon-delete" circle plain style="margin-top:14px;"></el-button>
                        </el-tooltip>

                        <el-dialog
                        title="注 意"
                        :visible.sync="dialogVisible"
                        width="30%">
                        <span>确定要删除该{{selectElement}}"{{selectName}}"？{{selectElement}}删除后不可恢复!</span>
                        <span slot="footer" class="dialog-footer">
                            <el-button @click="dialogVisible = false">取 消</el-button>
                            <el-button type="primary" @click="dialogVisible = false;deleteElement()">确 定</el-button>
                        </span>
                        </el-dialog>

                        <div style="margin-top:30px;font-size:14px;color:#b5b5b5;text-align:left;margin-left:40px;">
                            当前{{selectElement}}属性
                        </div>
                        <div class="table-content">
                            <el-table
                                :show-header="false"
                                :data="list_ch"
                                class="mt-10"
                                fit
                                empty-text="暂无数据"
                                :highlight-current-row="true"
                                style="margin-top:10px;"
                                max-height="260px"
                            >
                                <el-table-column align="center">
                                    <template slot-scope="scope">
                                    <template>
                                        <el-tag>{{scope.row.id}}</el-tag>
                                    </template>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                v-for="(item, index) in table_title"
                                :key="index"
                                :prop="item.prop"
                                :label="item.label"
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="更新" name="third" style="margin-top:60px;">

                        <div style="margin-top:40px;" @click="saveGraph()"><el-button round :icon="savebtnIcon">{{ savebtnText }}</el-button></div>
                        <el-dialog
                        title="保存"
                        :visible.sync="dialogVisible1"
                        width="30%"
                        center>
                        <span style="text-align:center;">图谱保存成功！</span>
                        <span class="dialog-footer" style="margin-top:40px;">
                            <el-button style="margin-top:20px;" @click="dialogVisible1 = false" icon="el-icon-check" type="success" round>确定</el-button>
                        </span>
                        </el-dialog>

                        <div style="margin-top:40px;" @click="dialogVisible2 = true"><el-button round icon="el-icon-upload2">增加数据</el-button></div>
                        <el-dialog
                        title="更新图谱"
                        :visible.sync="dialogVisible2"
                        width="30%">
                        <el-upload style="margin-top:10px;margin-bottom:20px;"
                        class="upload-demo"
                        :before-upload="getFileName"
                        action="http://127.0.0.1:8000/uploadjson/">
                        <el-button round plain type="primary" icon="el-icon-folder-opened">选择文件</el-button>
                        </el-upload>
                        <span class="dialog-footer" style="margin-top:40px;">
                            <el-button style="margin-top:20px;" @click="dialogVisible2 = false">取 消</el-button>
                            <el-button style="margin-top:20px;" type="primary" @click="uploadNewData()">上 传</el-button>
                        </span>
                        </el-dialog>

                    </el-tab-pane>
                </el-tabs>
            </el-aside>
        </el-container>
    </el-container>

</template>

<script>
import axios from 'axios'
import icon_url from '@/assets/icon-2.png'
import echarts from 'echarts'

export default {
    name:"upload",
    data() {
        return {
            placeholder:"请输入名称",
            input:'',
            graphName:"",
            dialogVisible: false,
            dialogVisible1: false,
            savebtnIcon: "el-icon-box",
            savebtnText:"保存图谱",
            dialogVisible2:false,
            deleteBtnShow:true,
            selectElement:'节点/关系',
            selectName: '',
            selectInfo:undefined,
            searchItem:undefined,
            checkStatus: "",
            choices:[],
            activeTab: 'first',
            iconPath:icon_url,
            data:[],
            links:[],
            entities:[],
            relations:[],
            activeName: 'first',
            
            // chartWidth: this.$ref.containerRef.offsetWidth-300+'px',
            // chartHeight: this.$ref.containerRef.offsetHeight-10+'px',
            chartWidth: 900+'px',
            chartHeight: 640+'px',

            table_title:[
                {
                    prop: 'input',
                    label: '属性',
                    width: '100',
                    titleAlign: 'center',
                    columnAlign: 'center',

                },
            ],
            list:[],
            list_ch:[],
            infoshow:true,
            myChart:undefined,
        }
    },
    created() {
        this.getRouterData()
    },
    methods: {
        searchEntity(entity){
            console.log(entity);
            axios.post("http://localhost:8000/get_entity/"+entity+"/",{
                    headers: {
                        'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'
                    }
                }).then(res => {
                    console.log(res);
                    this.refreshGraph(res.data.data,res.data.links,res.data.entities);
            });
        },

        searchRelation(relation){
            console.log(relation);
            axios.post("http://localhost:8000/get_relation/"+relation+"/",{
                headers: {
                    'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(res => {
                console.log(res);
                this.refreshGraph(res.data.data,res.data.links,res.data.entities);
            });
        },

        deleteElement(){
            var type = "";
            if(this.selectElement == "节点"){
                type = "node";
            }else if(this.selectElement == "关系"){
                type = "relation";
            };
            axios.post("http://localhost:8000/delete_"+type+"/",JSON.stringify(this.selectInfo),{
                headers: {
                    'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(res => {
                console.log(res);
                this.data = res.data.data;
                this.links = res.data.links;
                this.entities = res.data.entities;
                this.relations = res.data.relations;
                this.refreshGraph(res.data.data,res.data.links, res.data.entities);
            });
        },

        showElementOnly(){
            var type = "";
            if(this.selectElement == "节点"){
                type = "node";
            }else if(this.selectElement=="关系"){
                type = "relation";
            };
            axios.post("http://localhost:8000/show_"+type+"_only/",JSON.stringify(this.selectInfo),{
                headers: {
                    'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(res => {
                console.log(res);
                this.refreshGraph(res.data.data,res.data.links,res.data.entities);
            });
        },
        getFileName(file){
            this.$store.state.fileName=file.name.substring(0,file.name.length-5);
        },
        uploadNewData() {
            let data = this.$store.state.panel_data;
            // console.log(data);
            let fileName = this.$store.state.fileName;
            axios.post("http://localhost:8000/creategraph/"+fileName+"/",JSON.stringify(data),{
            headers: {
                'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'
            },
            }).then(res => {
                console.log(res);
                axios.get("http://localhost:8000/after_creation/").then(res=>{
                    this.data = res.data.data;
                    this.links = res.data.links;
                    this.entities = res.data.entities;
                    this.relations = res.data.relations;
                    this.refreshGraph(this.data, this.links, this.entities);
                })
            });
        },

        handleClick(tab, event) {
            console.log(tab,event);
        },

        getRouterData(){
            this.data = this.$route.params.data;
            this.links = this.$route.params.links;
            this.entities = this.$route.params.entities;
            this.relations = this.$route.params.relations;
            console.log("getRouterData");
            console.log(this.data);
            console.log(this.links);
        },
        show(){
            let echarts = require('echarts/lib/echarts');

            this.myChart = echarts.init(document.getElementById('myChart'));
            console.log(document.getElementById('myChart'));
            var categories = [];

            for (var i = 0; i < this.entities.length; i++) {

                categories[i] = {name: this.entities[i]};
            }


            let option = {
                // title: {text: 'ECharts 关系图'},

                tooltip: {
                    formatter: function (x) {
                    return x.data.des;
                    }
                },

                toolbox: {
                    show: true,
                    feature: {
                        mark: {
                        show: true
                        },
                        restore: {
                        show: true
                        },
                        saveAsImage: {
                        show: true
                        }
                    }
                },
                legend: [{
                    data: categories.map(function (a) {
                    return a.name;
                    })
                }],

                series: [{
                    type: 'graph', // 类型:关系图
                    layout: 'force', //图的布局，类型为力导图
                    symbolSize: 40, // 调整节点的大小
                    roam: true, // 是否开启鼠标缩放和平移漫游。默认不开启。如果只想要开启缩放或者平移,可以设置成 'scale' 或者 'move'。设置成 true 为都开启
                    edgeSymbol: ['circle', 'arrow'],
                    edgeSymbolSize: [2, 10],
                    edgeLabel: {
                        normal: {
                            textStyle: {
                            fontSize: 20
                            }
                        }
                    },
                    force: {
                    repulsion: 2500,
                    edgeLength: [10, 50]
                    },
                    draggable: true,
                    lineStyle: {
                        normal: {
                        width: 2,
                        color: '#4b565b',
                        }
                    },
                    edgeLabel: {
                        normal: {
                        show: true,
                        formatter: function (x) {
                            return x.data.name;
                        }
                        }
                    },
                    label: {
                        normal: {
                        show: true,
                        textStyle: {}
                        }
                    },
                    data: this.data,
                    links: this.links,
                    categories: categories,

                    // data: [{'name':'肺泡蛋白质沉积症','properties':{'test1':'okk','test2':'666'},'symbolSize':80,'category':'Disease'},{'name':'呼吸内科','symbolSize':70,'category':'Category'}],
                    // links:[{'target':'呼吸内科','source':'肺泡蛋白质沉积症','name':'category','des':'属于'}],
                    // categories: [{'name':'Disease'},{'name':'Category'}]
                }]
            };
            this.myChart.setOption(option);
            this.myChart.on('click', (params)  => {
                console.log(params);
                var data = params.data;
                this.activeName = 'second';
                this.deleteBtnShow = false;
                this.selectName = params.data.name;

                if(params.dataType == "node"){
                    this.selectElement = "节点";
                    this.selectInfo = {"name": params.data.name, "category":params.data.category};
                    this.list=[
                    {
                        id: "实体类别",
                        input: params.data.category,
                    }, {
                        id: "实体名称",
                        input: params.data.name,
                    }];
                    var properties = params.data.properties;
                    if(typeof(properties)!="undefined"){
                        this.list_ch = [];
                        for(var item in properties){
                        this.list_ch.push({
                            id:item,
                            input:properties[item],
                        })
                    }}else{
                        this.list_ch = [];
                    }

                }else if(params.dataType == "edge"){
                    this.selectElement = "关系";
                    this.selectInfo = {"name": params.data.name,"source": params.data.source, "target":params.data.target};
                    this.list=[
                    {
                        id: "关系类别",
                        input: params.data.name,
                    }, {
                        id: "连接实体",
                        input: params.data.source+'→'+params.data.target,
                    }];
                    var properties = params.data.properties;
                    if(typeof(properties)!="undefined"){
                        this.list_ch = [];
                        for(var item in properties){
                        this.list_ch.push({
                            id:item,
                            input:properties[item],
                        })
                    }}else{
                        this.list_ch = [];
                    }

                };

            });
            // this.myChart.bind('contextmenu', (conn, event) => {
            //         console.log(conn);
            // })

        },
        refreshGraph(data, links, entities){
            var categories = [];
            for (var i = 0; i < entities.length; i++) {

                categories[i] = {name: entities[i]};
            }
            var option = this.myChart.getOption();
            option.series[0].data = data;
            option.series[0].links = links;
            option.series[0].categories = categories;
            this.myChart.setOption(option);
        },

        querySearch(queryString, cb) {
            var choices = this.choices;
            var results = queryString ? choices.filter(this.createFilter(queryString)) : choices;
            // 调用 callback 返回建议列表的数据
            cb(results);
        },
        createFilter(queryString) {
            return (choice) => {
            return (choice.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
            };
        },
        loadAll(){
            var option = this.myChart.getOption();
            var data = option.series[0].data;
            var choices = [];
            for(var i=0;i<data.length;i++){
                choices.push({"value":data[i]["name"]})
            }
            return choices;
        },
        handleSelect(item) {
            console.log(item.value);
            this.searchItem = {"item": item.value};
        },
        searchQuery(){
            axios.post("http://localhost:8000/search_item/",JSON.stringify(this.searchItem),{
                headers: {
                    'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(res => {
                console.log(res);
                this.refreshGraph(res.data.data, res.data.links, res.data.entities);
            });
        },
        getDate(){
            var now = new Date();
            var year = now.getFullYear();    
            var month = now.getMonth() + 1;  
            var day = now.getDate();  
            var date = year.toString() + "." + month.toString() + "." + day.toString();   
            return date
        },
        saveGraph(){
            var name = this.$store.state.current_graph_name;
            var date = this.getDate();
            var info = {"name":name, "date": date, "type":"结构化文件","entities":this.entities, "relations":this.relations}
            console.log(info);
            this.savebtnIcon = "el-icon-loading";
            this.savebtnText = "正在保存";
            axios.post("http://localhost:8000/polls/save_graph/",JSON.stringify(info),{
                headers: {
                    'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(res => {
                console.log(res);
                this.dialogVisible1 = false;
                this.savebtnIcon = "el-icon-box";
                this.savebtnText = "保存图谱";
                this.$message({
                    message: '图谱保存成功!',
                    type: 'success'
                });
            });
            
        }


    },
    mounted: function(){
	    this.show();//需要触发的函数
        this.choices = this.loadAll();
        console.log(this.choices);
        this.graphName = this.$store.state.current_graph_name;
    }
}
</script>
<style scoped>
    #menu-aside{
        background-color: #2b3a49;
    }

    .main{
        background-color: #f3f3f4;
        margin-top:42px;
    }
    .main-container{
        position:absolute;
        height:100%;
        width:100%;
    }
    .card-box{
        margin-top:100px;
    }
    .tab-title{
        color:#fff;
    }
    .info{
        margin-top:42px;
    }



</style>